<template>
  <div class="form-container">
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><Document /></el-icon>
          <span>提交报销申请</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="left"
      >
        <!-- 申请人信息 -->
        <el-form-item label="申请人姓名" prop="applicantName">
          <el-input
            v-model="formData.applicantName"
            placeholder="请输入申请人姓名"
            clearable
            :prefix-icon="User"
          />
        </el-form-item>

        <!-- 报销金额 -->
        <el-form-item label="报销金额" prop="amount">
          <el-input-number
            v-model="formData.amount"
            :min="0"
            :precision="2"
            :step="0.01"
            placeholder="请输入报销金额"
            style="width: 100%"
            :prefix-icon="Money"
          />
        </el-form-item>

        <!-- 费用类型 -->
        <el-form-item label="费用类型" prop="expenseType">
          <el-select
            v-model="formData.expenseType"
            placeholder="请选择费用类型"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in expenseTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 报销事由 -->
        <el-form-item label="报销事由" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述报销事由，包括费用用途、时间、地点等"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 发票信息 -->
        <el-form-item label="发票信息" prop="invoiceInfo">
          <el-input
            v-model="formData.invoiceInfo"
            type="textarea"
            :rows="3"
            placeholder="请填写发票号码、开票日期等信息（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <!-- 表单操作按钮 -->
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit" :icon="Check">
            {{ loading ? '提交中...' : '提交申请' }}
          </el-button>
          <el-button @click="handleReset" :icon="Refresh"> 重置表单 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' // 引入Element Plus消息组件
import { Document, User, Money, Check, Refresh } from '@element-plus/icons-vue' // 引入图标
import { useApplicationStore } from '@/store/application'
import type { ReimbursementApplication } from '@/services/models'

// 定义表单数据接口
interface FormData {
  applicantName: string
  amount: number
  description: string
  expenseType: string
  invoiceInfo: string
}

// 费用类型选项
const expenseTypeOptions = [
  { value: 'office', label: '办公用品' },
  { value: 'travel', label: '差旅费用' },
  { value: 'entertainment', label: '招待费用' },
  { value: 'equipment', label: '设备采购' },
  { value: 'training', label: '培训费用' },
  { value: 'other', label: '其他费用' },
]

// 表单验证规则
const formRules = {
  applicantName: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  amount: [
    { required: true, message: '请输入报销金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' },
  ],
  expenseType: [{ required: true, message: '请选择费用类型', trigger: 'change' }],
  description: [
    { required: true, message: '请输入报销事由', trigger: 'blur' },
    { min: 10, max: 500, message: '事由长度在 10 到 500 个字符', trigger: 'blur' },
  ],
}

// 初始化表单数据
const formData = reactive<FormData>({
  applicantName: '',
  amount: 0,
  description: '',
  expenseType: '',
  invoiceInfo: '',
})

const store = useApplicationStore()
const loading = ref(false)
const formRef = ref() // 表单引用

// 声明emit，支持success事件
const emit = defineEmits<{
  success: [application: ReimbursementApplication]
}>()

// 提交表单处理函数
const handleSubmit = async () => {
  if (!formRef.value) return
  // 表单验证
  const valid = await formRef.value.validate()

  // 如果验证失败，直接返回，不执行后续逻辑
  if (!valid) {
    return
  }
  try {
    // 确认提交
    await ElMessageBox.confirm('确定要提交这个报销申请吗？', '确认提交', {
      confirmButtonText: '确定提交',
      cancelButtonText: '取消',
      type: 'info',
    })

    loading.value = true

    // 创建申请对象
    const application = {
      id: `app-${Date.now()}`,
      applicantId: store.currentUser.id,
      applicantName: formData.applicantName,
      amount: formData.amount,
      description: formData.description,
      expenseType: formData.expenseType,
      invoiceInfo: formData.invoiceInfo,
      status: 'PENDING_HEAD_REVIEW' as const,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      history: [
        {
          id: `rec-${Date.now()}`,
          approverId: store.currentUser.id,
          approverName: store.currentUser.name,
          action: 'submit' as const,
          comment: '提交申请',
          timestamp: new Date().toISOString(),
        },
      ],
    }

    // 提交申请
    await store.submitApplication(application)

    // 显示成功提示
    ElMessage({
      type: 'success',
      message: '申请提交成功！已进入部门主管审批流程。',
      duration: 3000,
    })

    // 重置表单
    if (formRef.value && formRef.value.resetFields) {
      formRef.value.resetFields()
    }

    // 触发成功事件，通知父组件申请提交成功，父组件可以据此关闭对话框或进行其他操作
    emit('success', application)
  } catch (error: unknown) {
    if (error !== 'cancel') {
      // 显示错误信息
      ElMessage({
        type: 'error',
        message: `提交失败：${error instanceof Error ? error.message : '未知错误'}`,
        duration: 5000,
      })
    }
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = async () => {
  if (!formRef.value) return

  try {
    await ElMessageBox.confirm('确定要重置表单吗？所有已填写的内容将被清空。', '确认重置', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 重置表单数据和验证状态
    if (formRef.value && formRef.value.clearValidate) {
      formRef.value.clearValidate()
    }

    ElMessage({
      type: 'info',
      message: '表单已重置',
      duration: 2000,
    })
  } catch {
    // 用户取消重置操作
  }
}
</script>

<style scoped>
.form-container {
  max-width: 700px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  border-radius: 12px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.card-header .el-icon {
  font-size: 20px;
  color: #409eff;
}

/* 自定义表单样式 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-input-number .el-input__wrapper) {
  border-radius: 8px;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 24px;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #337ecc 0%, #2c5aa0 100%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-container {
    padding: 10px;
  }

  :deep(.el-form-item__label) {
    width: 100px !important;
  }

  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
}

@media (max-width: 480px) {
  .form-container {
    padding: 5px;
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
    font-size: 14px;
  }
}
</style>
